/***************************************************************************
All validations and updates for WIN-BACK functionality 
Author: Bibhudutta Mishra
Updated By: Manish Tiwari Purpose: Removed Condition Closed and Lost(Reason)
Last Updated on : 26th Dec 2011    allowing win - back lead creation 
****************************************************************************/
trigger OORCheckWinBackLead on Lead (before insert,before update) {

Set<id> accIds = new Set<id>();
Map<id,List<Contact>> AccConListMap = new Map<id,List<Contact>>();
List<Contact> Contlist = new List<Contact>();
List<Contact> Contacts = new List<Contact>();
Map<id,Lead> LeadAccMap = new Map<id,Lead>();
List<Lead> UpdateLead = new List<Lead>();
Map<id,Lead> LeadOwnerMap = new Map<id,Lead>();
Set<id> accIds2 = new Set<id>();
List<Lead> LeadOwnerList = new List<Lead>();
List<Opportunity> OppList = new List<Opportunity>();
Map<id,Lead> LeadAccMapInsert = new Map<id,Lead>();

ID LeadRecordTypeID = RecordTypeHelper.GetRecordTypeID('Lead', 'Local Advertiser');

        for(Lead ld:Trigger.new){ 
                if(ld.Win_Back_Account__c != null &&(ld.recordtypeId == LeadRecordTypeID)&& (Trigger.ISINSERT || (Trigger.ISUPDATE && Trigger.oldMap.get(ld.Id).Phone != ld.Phone))){
                        accIds.add(ld.Win_Back_Account__c);
                        LeadAccMap.put(ld.Win_Back_Account__c,ld);
                        if(Trigger.ISINSERT){
                            ld.LeadSource = 'Win-Back';
                            LeadOwnerMap.put(ld.ownerId,ld);
                            accIds2.add(ld.Win_Back_Account__c);
                            LeadAccMapInsert.put(ld.Win_Back_Account__c,ld);
                        }
                    
                }
                
        }
    //Code for checking Contact phone
    if(accIds.Size()>0){
    Contlist = [Select Phone,Id,AccountId from Contact where AccountId IN: accIds];
       for(Id accid:accIds){
           Contacts.clear();
        for(Contact cont:Contlist){
            if(accid == cont.AccountId){
                Contacts.add(cont);
            }
            
        }
        AccConListMap.put(accid,Contacts);
        }
       } 
        
        
    for(Id acc:LeadAccMap.keySet()){
        for(Id accs:AccConListMap.keySet()){
            if(acc == accs){
                for(Contact cnt:AccConListMap.get(accs)){
                    if(LeadAccMap.get(acc).Phone==cnt.phone){
                      LeadAccMap.get(acc).OOR_Contact_Convert_Map__c = cnt.Id;
                      UpdateLead.add(LeadAccMap.get(acc)); 
                      break; 
                    }
                }
            }
        }        
    
    }
    //Code for checking duplicate Win-Back Leads
    if(accIds2.Size()>0){
    LeadOwnerList = [Select id,OwnerId,Win_Back_Account__c from Lead where OwnerId IN: LeadOwnerMap.keySet()and Win_Back_Account__c IN:accIds2 and ISCONVERTED=FALSE];
    If(LeadOwnerList.size()>0){
        for(Lead leads:LeadOwnerList){
            for(id own:LeadOwnerMap.keySet()){
                if((leads.ownerId == own)&&(leads.Win_Back_Account__c == LeadOwnerMap.get(own).Win_Back_Account__c)){
                    LeadOwnerMap.get(own).Win_Back_Account__c.addError('You already have created a Win-Back Lead on this Account, So you cannot create another');
                }
            }
        }
    }
    }
    //Code for checking Orders with valid status and restrict lead creation
    if(accIds2.Size()>0){
    OppList = [Select Id,StageName,AccountId from Opportunity where AccountId IN: accIds2 and  ( StageName = 'Solo Order Pending' OR StageName = 'Signed Contract' )];
    If(OppList.Size()>0){ 
    for(Opportunity Opp:OppList){
        for(id accid:LeadAccMapInsert.keySet()){
            if(Opp.AccountId==accid){
                LeadAccMapInsert.get(accid).Win_Back_Account__c.addError('You cannot create a winback lead against an account that has already a pending order being processed');
            }
        }                  
    }
  }    
 } 
}